# coding: utf-8
import json
from pathlib import Path

from PySide6.QtCore import QStandardPaths, Qt
from PySide6.QtWidgets import QFileDialog, QHBoxLayout
from qfluentwidgets import FluentIcon as FIF, TransparentToolButton, TransparentPushButton, BodyLabel, IconWidget

from common import openUrl, Icon, cfg, signalBus, Task
from .headers_dialog import HeadersDialog
from ..widgets import Alert, ScrollAreaMessageBox, ExpandCardWidget, ElPlainTextEdit


class AddDialogBase(ScrollAreaMessageBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__type = 'Link'

        self.urlEdit = ElPlainTextEdit(self)
        self.nameEdit = ElPlainTextEdit(self)
        self.saveCard = ExpandCardWidget(FIF.SAVE, '保存到', self)
        self.headersCard = ExpandCardWidget(FIF.HEADPHONE, '请求头', self)
        self.headers = {'user-agent': cfg.get(cfg.userAgent)}

        self.openSaveBtn = TransparentPushButton(
            QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DownloadLocation), self)
        self.selectSaveBtn = TransparentToolButton(FIF.FOLDER_ADD, self)
        self.headersBtn = TransparentPushButton(FIF.ADD_TO, '添加请求头', self)

        self.__initWidgets()
        self.__connectSignals()

    def __initWidgets(self):
        # 设置控件属性
        self.yesButton.setText('提交')
        self.urlEdit.setPlaceholderText('请输入HTTP/HTTPS链接, 多个链接请用英文逗号 `,` 隔开')
        self.nameEdit.setPlaceholderText('请输入文件名, 多个文件名请用英文逗号 `,` 隔开, 如 `01.mp4, 02.mp4`')

        self.scrollArea.setContentsMargins(0, 0, 0, 0)
        self.scrollArea.setSpacing(10)
        self.scrollArea.addLayout(self.createLayout(Icon.LINK, '下载链接'), 0)
        self.scrollArea.addWidget(self.urlEdit, 1)
        self.scrollArea.addLayout(self.createLayout(FIF.QUICK_NOTE, '文件名'), 0)
        self.scrollArea.addWidget(self.nameEdit, 1)
        self.scrollArea.addWidget(self.saveCard)
        self.scrollArea.addWidget(self.headersCard)
        # 添加子控件
        self.saveCard.addWidget(self.openSaveBtn, 1)
        self.saveCard.addWidget(self.selectSaveBtn, 0)
        self.headersCard.addWidget(self.headersBtn, 0, Qt.AlignmentFlag.AlignRight)

    def setType(self, tp: str):
        self.__type = tp

    def type(self) -> str:
        return self.__type

    def createLayout(self, icon, text):
        hl = QHBoxLayout()
        hl.setAlignment(Qt.AlignmentFlag.AlignLeft)
        iw = IconWidget(icon, self)
        iw.setFixedSize(16, 16)
        hl.addWidget(iw)
        hl.addWidget(BodyLabel(text, self))
        return hl

    def __connectSignals(self):
        self.openSaveBtn.clicked.connect(lambda: openUrl(self.openSaveBtn.text()))
        self.selectSaveBtn.clicked.connect(self.selectSaveFolder)
        self.headersBtn.clicked.connect(self.onHeadersBtnClicked)

    def onHeadersBtnClicked(self):
        _, headers = HeadersDialog.showDialog('URL 请求头', self)
        if _:
            self.headers = headers

    def selectSaveFolder(self):
        folder = QFileDialog.getExistingDirectory(self, '选择文件夹', QStandardPaths.writableLocation(
            QStandardPaths.StandardLocation.DownloadLocation))
        if folder:
            self.openSaveBtn.setText(folder)

    def validate(self) -> bool:
        urls = self.urlEdit.toPlainText().strip().split(',')
        names = self.nameEdit.toPlainText().strip().split(',')
        save_folder = self.openSaveBtn.text()
        if not urls or not names:
            Alert.warning('请填写下载链接和文件名')
            return False
        if len(urls) != len(names):
            Alert.warning('下载链接和文件名数量不匹配')
            return False

        for url, name in zip(urls, names):
            url = url.strip()
            name = name.strip()
            if not url or not name:
                Alert.warning('请填写完整的下载链接和文件名')
                return False
            if not (url.startswith('http://') or url.startswith('https://')):
                Alert.warning('请填写正确的下载链接')
                return False
            save_file = Path(f'{save_folder}/{name}')
            if save_file.exists():
                Alert.error(f'{save_file} 已存在，请重命名')
                return False
            signalBus.taskAddedSig.emit(
                Task(
                    url=url,
                    file_name=name,
                    save_folder=save_folder,
                    headers=json.dumps(self.headers),
                    type=self.type()
                )
            )

        return True


class AddLinkDialog(AddDialogBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle('HTTP/HTTPS 下载')
        self.setType('Link')


class AddM3u8Dialog(AddDialogBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle('M3U8 下载')
        self.setType('M3U8')
